<?php

require 'Class/Aliyun/v1/sdk.class.php';

require 'Class/Aliyun/v1/function.php';

class Aliyunv1Action extends AdminbaseAction{

	public $service ;
	public $hz_host = '.oss-cn-hangzhou.aliyuncs.com/';
	public $nw_host = '.oss-internal.aliyuncs.com/';
	public $qd_host = '.oss-cn-qingdao-internal.aliyuncs.com/';
	public $host 	= '.oss.aliyuncs.com/';

	public function _initialize(){

		parent::_initialize();

	    $AccessKeyId = 'VQJnfORAnHvNE7S2';
	    $AccessKeySecret = 'oZ4ollH8yl3JfZDFFRmKYltB6aDxxU';

		$this->service = new ALIOSS($AccessKeyId,$AccessKeySecret);

		//设置是否打开curl调试模式
		$this->service->set_debug_mode(TRUE);
    	$this->bucket	= 'pchb8';
    	$this->web_name = 'pchb8';
	}

	/**
	 * 阿里云OSS文件管理
	 * @return [type] [description]
	 */
	public function  index(){
        $all_size = M('cloudfile')->where("cloud_type = 'aliyun'")->sum('size');
        $this->all_size = $all_size;
		$list = M('cloudfile')->where("cloud_type = 'aliyun'")->order('create_time DESC')->select();
		$this->assign('list',$list);
		// print_r($list);
		$this->display();
		// echo $this->upload_by_content('qiaogen','1','hengjia/txt/'.time().'.txt');
		// print_r($this->upload_by_file('qiaogen','data/images/noimg.png','hengjia/img/noimg.png'));
		// print_r($this->delete_object('qiaogen','hengjia/img/noimg.png'));
		// $keys = array(
		// 	'hengjia/img/noimg.png','hengjia/img/noimg1.png'
		// );
		// print_r($this->delete_objects('qiaogen',$keys));
	}

	/**
	 * 百度编辑器上传
	 * @return [type] [description]
	 */
	public function ueditorUp(){
	    //获取存储目录
	    if ( isset( $_GET[ 'fetch' ] ) ) {
	        header( 'Content-Type: text/javascript' );
	        echo 'updateSavePath('. json_encode('/') .');';
	        return;
	    }

	    // print_r($_FILES);
	    // 
    	$file 		= $_FILES['upfile'];
    	$file_name  = $file['name'];
    	$tmp 		= $file['tmp_name'];
    	$size 		= $file['size'];

    	$type = $_GET['type']?$_GET['type']:'img';

    	$rand_str   = '-'.rand(1,100).rand(100,2000);
    	$save_path = "$this->web_name/$type/".date("Ymd").'/'.time().$rand_str.$this->getFileExt($file_name);

    	// echo $save_path;exit;
    	// 
    	$fp = fopen($tmp, 'r');
    	while (!feof($fp)) {
    		$content .= fgets($fp);
    	}
    	// echo $content;

    	$url = $this->upload_by_content($this->bucket,$content,$save_path);

    	fclose($fp);

    	// echo $url;exit;

    	if(! empty($url) ){
    		$json = array(
    			'url' => $url,
    			'title' => $file_name,
    			'original' => $file_name,
    			'state' => 'SUCCESS',
    		);

    		$data = array(
    			'user_id' => 0,
    			'term_id' => 0,
    			'object_id' => 0,
    			'cloud_type' => 'aliyun',
    			'key' => $save_path,
    			'file_name' => $file_name,
    			'file_type' => $this->getFileExt($file_name),
    			'url' => $url,
    			'size' => $size,
    			'create_time' => time()
    		);

    		$fid = M('cloudfile')->add($data);

    		if($fid){
    			echo json_encode($json);
    		}else{
    			echo json_encode(array('state'=>'写入数据库错误'));
    		}
    		
    	}else{
    		echo json_encode(array('state'=>'上传错误'));
    	}
	}

	/**
	 * 百度编辑器上传
	 * @return [type] [description]
	 */
	public function ueditorFileUp(){

	    // print_r($_FILES);
	    // 
    	$file 		= $_FILES['upfile'];
    	$file_name  = $file['name'];
    	$tmp 		= $file['tmp_name'];
    	$size 		= $file['size'];
    	
    	$rand_str   = '-'.rand(1,100).rand(100,2000);
    	$save_path = "$this->web_name/file/".date("Ymd").'/'.time().$rand_str.$this->getFileExt($file_name);

    	// echo $save_path;exit;
    	// 
    	$fp = fopen($tmp, 'r');
    	while (!feof($fp)) {
    		$content .= fgets($fp);
    	}
    	// echo $content;

    	$url = $this->upload_by_content($this->bucket,$content,$save_path);

    	fclose($fp);

    	// echo $url;exit;

    	if(! empty($url) ){



    		$data = array(
    			'user_id' => 0,
    			'term_id' => 0,
    			'object_id' => 0,
    			'cloud_type' => 'aliyun',
    			'key' => $save_path,
    			'file_name' => $file_name,
    			'file_type' => $this->getFileExt($file_name),
    			'url' => $url,
    			'size' => $size,
    			'create_time' => time()
    		);

    		$fid = M('cloudfile')->add($data);

    		$json = array(
    			'url' => $url,
    			'fileType' => $this->getFileExt($file_name),
    			'original' => $file_name,
    			'state' => 'SUCCESS',
    		);
    /**
     * 向浏览器返回数据json数据
     * {
     *   'url'      :'a.rar',        //保存后的文件路径
     *   'fileType' :'.rar',         //文件描述，对图片来说在前端会添加到title属性上
     *   'original' :'编辑器.jpg',   //原始文件名
     *   'state'    :'SUCCESS'       //上传状态，成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
     * }
     */
    		if($fid){
    			echo json_encode($json);
    		}else{
    			echo json_encode(array('state'=>'写入数据库错误'));
    		}
    		
    	}else{
    		echo json_encode(array('state'=>'上传错误'));
    	}
	}

	/**
	 * 阿里云OSS缩略图上传
	 * @param  [type] $file [description]
	 * @return [type]       [description]
	 */
    public function swfUp($file){
        // print_r($file);
        // exit;
        $file_name = $file['name'];
        $tmp = $file['tmp_name'];
        $size = $file['size'];

    	$rand_str   = '-'.rand(1,100).rand(100,2000);
    	$save_path = "$this->web_name/img/".date("Ymd").'/'.time().$rand_str.$this->getFileExt($file_name);

    	$fp = fopen($tmp, 'r');
    	while (!feof($fp)) {
    		$content .= fgets($fp);
    	}
    	// echo $content;

    	$url = $this->upload_by_content($this->bucket,$content,$save_path);

    	fclose($fp);

        $data = array(
            'user_id' => 0,
            'term_id' => 0,
            'object_id' => 0,
            'cloud_type' => 'aliyun',
            'key' => $save_path,
            'file_name' => $file_name,
            'file_type' => $this->getFileExt($file_name),
            'url' => $url,
            'size' => $size,
            'create_time' => time()
        );
        $fid = M('cloudfile')->add($data);

        echo "1," .$url.",".'1,'.$file_name;
    }


	/**
	 * 删除文件
	 * 阿里云OSS v1
	 * @return [type] [description]
	 */
	public function deleteFile(){

    	if($_GET['id']){
	   		$id = $_GET['id'];
	    	$key = M('cloudfile')->where('id='.$id)->getField('key');

	    	$des = M('cloudfile')->where('id='.$id)->delete();
	    	$res = $this->delete_object($this->bucket,$key);
	    	// 需要注意 阿里云删除返回的和又拍云是不一样的
	    	if($res && $des){
	    		$this->success('删除成功');
	    	}else{
	    		$this->error('删除失败');
	    	}
    	}

    	if($_POST['ids']){
    		foreach ($_POST['ids'] as $key => $value) {
    			$keys[] = M('cloudfile')->where('id='.$value)->getField('key');

    			// 删一个
    			// $key = M('cloudfile')->where('id='.$value)->getField('key');
    			// $res = $this->delete_object($this->bucket,$key);
       			$des = M('cloudfile')->where('id='.$value)->delete();
    		}

    		// 删除多个 总是有返回的
    		$res = $this->delete_objects($this->bucket,$keys);

	    	if($res && $des){
	    		$this->success('删除成功');
	    	}else{
	    		$this->error('删除失败');
	    	}
    	}

	}

    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt($name)
    {
        return strtolower( strrchr( $name , '.' ) );
    }

	/**
	 * 通过内容上传文件
	 * @param  string $bucket  [description]
	 * @param  string $content [description]
	 * @param  string $key     [description]
	 * @return [type]          [description]
	 */
	public function upload_by_content($bucket='',$content='',$key=''){
		$upload_file_options = array(
			'content' => $content,
			'length' => strlen($content),
			ALIOSS::OSS_HEADERS => array(
				// 'Expires' => '2012-10-01 08:00:00',
			),
		);
		$response = $this->service->upload_file_by_content($bucket,$key,$upload_file_options);
		if($response->isOk()){
			return 'http://'.$bucket.$this->host.$key;
		}else{
			return false;
		}
	}

	/**
	 * 通过目录上传
	 * @param  [type] $obj [description]
	 * @return [type]      [description]
	 */
	public function upload_by_file($bucket='',$file_path='',$key=''){

		$response = $this->service->upload_file_by_file($bucket,$key,$file_path);
		
		if($response->status == 200){
			return $response->header['x-oss-request-url'];
		}else{
			return false;
		}
		
	}

	/**
	 * 删除object
	 * @param  [type] $obj [description]
	 * @return [type]      [description]
	 */
	public function delete_object($bucket='',$key=''){
		if (empty($key)) return false;
		$response = $this->service->delete_object($bucket,$key);
		return true;
	}

	/**
	 * 删除objects
	 * @param  [type] $obj [description]
	 * @return [type]      [description]
	 */
	public function delete_objects($bucket='',$keys=''){
		if(empty($keys) && !is_array($keys)) return false;
		$options = array(
			'quiet' => false,
			//ALIOSS::OSS_CONTENT_TYPE => 'text/xml',
		);
		
		$response = $this->service->delete_objects($bucket,$keys,$options);
		
		return $response;
	}
}  // END